package com.cash.app.ui.start

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.webkit.WebView
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.cash.app.R
import com.cash.app.application.AppInitializer
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcPermissionBinding
import com.cash.app.ui.main.MainActivity
import com.cash.app.utils.SpUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class PermissionActivity : BaseActivity() {

    private lateinit var binding: AcPermissionBinding
    private lateinit var webView: WebView
    private lateinit var checkboxAgree: CheckBox
    private lateinit var btnReject: TextView
    private lateinit var btnNext: TextView

    private val requiredPermissions = arrayOf(
        Manifest.permission.READ_SMS,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.CAMERA
    )

    private var deniedPermissions = mutableListOf<String>()
    private var isSecondRequest = false

    // Permission request launcher
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        handlePermissionResult(permissions)
    }

    override fun setViewBind() {
        binding = AcPermissionBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        setupWebView()
    }

    private fun initView() {
        webView = binding.webView
        checkboxAgree = binding.checkboxAgree
        btnReject = binding.btnReject
        btnNext = binding.btnNext

        // Reject button click
        btnReject.setOnClickListener {
            finish()
        }

        // Next button click
        btnNext.setOnClickListener {
            if (!checkboxAgree.isChecked) {
                toast(getString(R.string.permission_not_agree))
                return@setOnClickListener
            }
            requestPermissions()
        }
    }

    private fun setupWebView() {
        // Disable JavaScript and web content loading
        webView.settings.javaScriptEnabled = false

        // Load local HTML file
        webView.loadUrl("file:///android_asset/permissions.html")
    }

    private fun requestPermissions() {
        deniedPermissions.clear()

        // Check which permissions are not granted
        for (permission in requiredPermissions) {
            if (ContextCompat.checkSelfPermission(
                    this, permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                deniedPermissions.add(permission)
            }
        }

        when {
            deniedPermissions.isEmpty() -> {
                // All permissions are granted
                navigateToMain()
            }

            else -> {
                // Request permissions
                requestPermissionLauncher.launch(deniedPermissions.toTypedArray())
            }
        }
    }

    private fun handlePermissionResult(permissions: Map<String, Boolean>) {
        deniedPermissions.clear()

        // Check for denied permissions
        permissions.forEach { (permission, isGranted) ->
            if (!isGranted) {
                deniedPermissions.add(permission)
            }
        }

        when {
            deniedPermissions.isEmpty() -> {
                // All permissions granted
                navigateToMain()
            }

            isSecondRequest -> {
                // Show settings dialog if this was the second request
                showSettingsDialog()
            }

            else -> {
                // First request failed, try second time
                isSecondRequest = true
                requestPermissionLauncher.launch(deniedPermissions.toTypedArray())
            }
        }
    }

    private fun showSettingsDialog() {
        AlertDialog.Builder(this).setTitle(getString(R.string.tips))
            .setMessage(getString(R.string.permission_guide_tips)).setCancelable(false)
            .setNegativeButton(getString(R.string.btn_reject)) { _, _ ->
                // Force close app
                finish()
            }.setPositiveButton(getString(R.string.go_setting)) { _, _ ->
                // Open app settings
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.fromParts("package", packageName, null)
                startActivity(intent)
                finish()
            }.show()
    }

    private fun navigateToMain() {
        SpUtils.put(AppConstant.K_PP_GRANTED, true)
        AppInitializer.startInit(application)
        lifecycleScope.launch {
            delay(200)
            if (!isFinishing) {
                jumpToPage()
            }
        }
    }

    private fun jumpToPage() {
        startActivity(Intent(this@PermissionActivity, MainActivity::class.java))
        finish()
    }

    private fun toast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
    }
} 